package com.huawei.translate.provider;

import com.huawei.translate.vo.translate.TranslateRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.text.NumberFormat;

@Component
public class TranslateProviderFactory {

    private static final Logger LOG = Logger.getLogger(TranslateProviderFactory.class);

    @Autowired
    private MSTranslateProvider msTranslateProvider;

    @Autowired
    private YoudaoTranslateProvider youdaoTranslateProvider;

    private NumberFormat format = DecimalFormat.getPercentInstance();

    @Autowired
    private HuaWeiTranslateProvider huaWeiTranslateProvider;

    @Value("${route.youdao}")
    private String youdaoRouteConfigRate = "80%";

    public TranslateProvider getProvider(TranslateRequest request) {

        if (request.shouldDispatchtoMS()) {
            LOG.info("Route to ms provide.");
            return msTranslateProvider;
        }

        if (generateHashValue() < getYouDaoProportion()) {
            LOG.info("Route to youdao provide.");
            return youdaoTranslateProvider;
        }

        LOG.info("Route to huawei provide.");
        return huaWeiTranslateProvider;
    }


    public float getYouDaoProportion() {
        LOG.info("youdao config rate : " + youdaoRouteConfigRate);
        float youdaoRouteRate = parseYouDaoProportion(youdaoRouteConfigRate) * 100;
        LOG.info("youdao route rate : " + youdaoRouteRate);
        return youdaoRouteRate;
    }

    public long generateHashValue() {
        return System.currentTimeMillis() % 100;
    }

    public float parseYouDaoProportion(String youdaoRate) {
        try {
            Number number = format.parse(youdaoRate);
            return number.floatValue();
        } catch (Exception ex) {
            return 0;
        }
    }
}
